package jmconf

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/BurntSushi/toml"
	"github.com/zeast/logs"
)

//Cfg the local config
var (
	cfgPath string
	Cfg     LocalCfg
)

//DisCfg discribution config center zk/etcd/consul config
type DisCfg struct {
	Type       string   `toml:"type"`
	Addrs      []string `toml:"addrs"`
	Path       string   `toml:"path"`
	Timeout    int64    `toml:"timeout"`
	Token      string   `toml:"token"`
	DataCenter string   `toml:"datacenter"`
}

//LocalCfg local config. zk, etcd, consul...
type LocalCfg struct {
	Listen       string `toml:"listen"`
	APIServer    string `toml:"apiServer"`
	Role         string `toml:"role"`
	StatsD       string `toml:"statsD"`
	LogPath      string `toml:"logPath"`
	LogLvl       string `toml:"logLevel"`
	HostName     string `toml:"hostName"`
	MaxOpenFiles int64  `toml:"maxOpenFiles"`
	UmsAgentAddr string `toml:"umsAgentAddr"`
	GetMysqlConnTimeout uint32 `toml:"getMysqlConnTimeout"`
	DisCfg       DisCfg
}

//Init Config
func Init(path string) {
	cfg, err := loadConfig(path)
	if err != nil {
		fmt.Println(err)
		os.Exit(-2)
	}
	cfgPath = path
	Cfg = *cfg
}

func loadConfig(path string) (cfg *LocalCfg, err error) {
	if path == "" {
		return nil, errors.New("Parse --config= error")
	}
	content, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("Parse file:%s error", path)
	}
	cfg = new(LocalCfg)
	if err := toml.Unmarshal(content, cfg); err != nil {
		return nil, fmt.Errorf("Parse content error: %s", string(content))
	}

	logs.Infof("Run With Cfg: %s \n%#v\n", path, cfg)
	return cfg, nil
}

//ReloadConfig reload config
func ReloadConfig() error {
	cfg, err := loadConfig(cfgPath)
	if err != nil {
		return err
	}
	Cfg = *cfg
	return nil
}
